package com.leejxx.health.mobile.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.leejxx.health.common.MessageConst;
import com.leejxx.health.common.RedisConst;
import com.leejxx.health.entity.Result;
import com.leejxx.health.pojo.Setmeal;
import com.leejxx.health.service.CheckMealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.hamcrest.Matchers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author LeeJx
 * @ClassName SetMealController
 * @Description TODO
 * @date 2021/1/4 20:57
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/mobile/setMeal")
public class SetMealController {

    @DubboReference
    private CheckMealService checkMealService;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/getSetMeal")
    public Result getSetMeal() {
        List<Setmeal> checkMeals=new ArrayList<>();
        if (!redisTemplate.hasKey(RedisConst.FIND_ALL_CHECKMEAL)){
            checkMeals = checkMealService.findAllCheckMeal();
            redisTemplate.boundListOps(RedisConst.FIND_ALL_CHECKMEAL).leftPush(checkMeals);
            redisTemplate.boundListOps(RedisConst.FIND_ALL_CHECKMEAL).expire(30,TimeUnit.MINUTES);
        }else {
            checkMeals= (List<Setmeal>) redisTemplate.boundListOps(RedisConst.FIND_ALL_CHECKMEAL).index(0);
        }

        log.info("[移动端套餐管理-查询套餐列表]data:{}", checkMeals);
        return new Result(true, MessageConst.QUERY_SETMEALLIST_SUCCESS, checkMeals);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        log.info("[移动端套餐管理-查询套餐细节]id:{}", id);
        Setmeal setMeal = null;
        if (!redisTemplate.hasKey(RedisConst.FIND_CHECKMEAL+id)){
            setMeal = checkMealService.findById(id);
            String s = JSON.toJSONString(setMeal);
            redisTemplate.boundValueOps(RedisConst.FIND_CHECKMEAL+id).set(s);
            redisTemplate.boundValueOps(RedisConst.FIND_CHECKMEAL).expire(30,TimeUnit.MINUTES);
        }
        String o = (String) redisTemplate.boundValueOps(RedisConst.FIND_CHECKMEAL+id).get();
        setMeal = JSONObject.parseObject(o, Setmeal.class);
        return new Result(true, MessageConst.QUERY_SETMEALLIST_SUCCESS, setMeal);
    }

}
